import { VNode, h } from "vue";
import { type RouteRecordNameGeneric, RouteRecordRaw } from "vue-router";

const routerMap = new Map();

/**
 * 根据route的name设置对应component的name
 * @param name
 * @param component
 * @returns VNode
 */
export function componentNameByRoute(
  name: RouteRecordNameGeneric,
  component: VNode
): VNode | undefined {
  if (!name || !component) {
    return undefined;
  }
  let comp;
  if (routerMap.has(name)) {
    comp = routerMap.get(name);
  } else {
    comp = {
      name: name,
      render: () => component
    };
    routerMap.set(name, comp);
  }
  return h(comp);
}

/**
 * 获取所有的routes
 * @returns { allRoutes, constantRoutes, authRoutes }
 */
export function getRoutes() {
  const modules = import.meta.glob("../router/modules/**/*.ts", {
    eager: true,
    import: "default"
  });
  const constantRoutes = [],
    authRoutes = [];
  for (const key in modules) {
    for (const o of modules[key] as RouteRecordRaw[]) {
      if (o?.meta?.constant) {
        constantRoutes.push(Object.assign(o));
      } else {
        authRoutes.push(o);
      }
    }
  }
  return {
    allRoutes: [...constantRoutes, ...authRoutes],
    constantRoutes,
    authRoutes
  };
}

/**
 * 获取不缓存的路由
 * @returns RouteRecordRaw[]
 */
export function getExcludeCacheRoutes() {
  const { allRoutes } = getRoutes();
  const r = [];
  for (const o of allRoutes) {
    if (o?.meta?.keepAlive === false) {
      r.push(o.name);
    }
  }
  return r;
}
